<template>
  <Modal
    v-model:visible="visible"
    style="width: 450px; top: 50px"
    title="修改密码"
    :footer="null"
    :closable="props.closable"
    :keyboard="false"
    :maskClosable="false"
    destroyOnClose
  >
    <Form
      layout="vertical"
      :model="state"
      :rules="rules"
      autocomplete="off"
      @finish="submitModal"
    >
      <SuScrollbar max-height="calc(100vh - 230px)">
        <div class="modal-body">
          <FormItem v-if="props.isLogin">
            <div class="m-row-side">
              <span class="blueTxt size13"
                >由于您长时间未更新密码，密码已过期。请您修改密码后再重新登录！</span
              >
            </div>
          </FormItem>
          <FormItem>
            <div class="m-row-side">
              <span>用户名：{{ props.name }}</span>
            </div>
          </FormItem>
          <FormItem>
            <div class="m-row-side">
              <span class="redTxt size13">{{ pwdLevel.tip }}</span>
            </div>
          </FormItem>
          <FormItem label="旧密码：" name="oldPWD">
            <InputPassword
              v-model:value.trim="state.oldPWD"
              size="large"
              allow-clear
              placeholder="请输入旧密码..."
            />
          </FormItem>
          <FormItem label="新密码：" name="newPWD">
            <InputPassword
              v-model:value.trim="state.newPWD"
              size="large"
              allow-clear
              placeholder="请输入新密码..."
            />
          </FormItem>
          <FormItem label="确认密码：" name="truePWD">
            <InputPassword
              v-model:value.trim="state.truePWD"
              size="large"
              allow-clear
              placeholder="请再次输入新密码..."
            />
          </FormItem>
        </div>
      </SuScrollbar>
      <FormItem class="form-footer">
        <Button type="primary" html-type="submit" :loading="state.loading"
          >确定</Button
        >
      </FormItem>
    </Form>
  </Modal>
</template>

<script setup lang="ts">
import SuScrollbar from 'components/src/su-scrollbar/index.vue';
import { Modal, FormItem, Button, Form, InputPassword } from 'ant-design-vue';
import { computed, reactive, ref } from 'vue';
import {md5} from 'js-md5';
import homeApi from 'apis/src/portal/home';
import userApi from "apis/src/users/common";

// 密码等级配置，默认强密码
const pwdConfig = {
  strong: {
    tip: '* 密码需包含字母、数字和符号至少2种，长度为8-16位！',
    regPwd:
      /^(?=.*\d)(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^[^\s\u4e00-\u9fa5]{8,16}$/,
  },
  simple: {
    tip: '* 密码需长度为8-16位！',
    regPwd: /^.{8,16}$/,
  },
};
const pwdLevel = ref(pwdConfig.strong);
const configKey = 'user.pwd.level';
userApi.getCustomConfigByKeys([configKey]).then((res) => {
  const key = res.data[configKey] as keyof typeof pwdConfig;
  pwdLevel.value = pwdConfig[key] || pwdConfig.strong;
});

const props = defineProps({
  show: Boolean,
  name: String,
  closable: Boolean,
  isLogin: Boolean, // 是否是登录页进入
  token: String,
});
const emit = defineEmits(['update:show', 'callback']);
const visible = computed({
  get: () => props.show,
  set: (val) => {
    state.oldPWD = '';
    state.newPWD = '';
    state.truePWD = '';
    emit('update:show', val);
  },
});
const state = reactive({
  loading: false,
  oldPWD: '',
  newPWD: '',
  truePWD: '',
});

// 自定义校验规则
const validatorPWD = (_rule: {field: string}, value: string) => {
  if (_rule.field === 'oldPWD') {
    if (!value) return Promise.reject(new Error('旧密码不能为空！'));
    return true;
  } else {
    const regPWD = pwdLevel.value.regPwd;
    if (!regPWD.test(value)) {
      return Promise.reject(new Error('密码格式不对！'));
    }
    if (_rule.field === 'newPWD' && state.oldPWD === value) {
      return Promise.reject(new Error('新密码不能与旧密码相同！'));
    }
    if (_rule.field === 'truePWD' && state.newPWD !== value) {
      return Promise.reject(new Error('两次输入的新密码不一致！'));
    }
  }
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const rules:any  = {
  oldPWD: [
    {
      required: true,
      validator: validatorPWD,
      trigger: 'change',
    },
  ],
  newPWD: [
    {
      required: true,
      validator: validatorPWD,
      trigger: 'change',
    },
  ],
  truePWD: [
    {
      required: true,
      validator: validatorPWD,
      trigger: 'change',
    },
  ],
};

// 确定
const submitModal = () => {
  state.loading = true;
  const { oldPWD, truePWD } = state;
  const params = {
    oldPassword: md5(md5(oldPWD)),
    newPassword: md5(md5(truePWD)),
  };
  const { isLogin, token } = props;
  if (isLogin && token) {
    localStorage.setItem('token', token);
  }

  homeApi
    .changePWD(params)
    .then(() => {
      let second = 3;
      let isOut = false;
      const modal = Modal.success({
        title: `操作成功，将于${second}s后退出系统！`,
        okText: '立即退出',
        onOk() {
          isOut = true;
          emit('callback');
        },
      });
      const timer = setInterval(() => {
        second--;
        modal.update({ title: `操作成功，将于${second}s后退出系统！` });
        if (second <= 0) {
          clearInterval(timer);
          second = 3;
          modal.destroy();
          if (!isOut) {
            emit('callback');
          }
        }
      }, 1000);
    })
    .catch(() => {
      state.loading = false;
      localStorage.removeItem('token');
      localStorage.removeItem('isPwdExpired');
    });
};
</script>
